package com.ingweb.inventarius.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.ingweb.inventarius.dao.DAOBodega;
import com.ingweb.inventarius.model.Bodega;

public class DAOBodegaImpl implements DAOBodega {

	private static Logger logger = Logger.getLogger(DAOBodegaImpl.class);
	
	@Override
	public List<Bodega> obtenerBodegas() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		List<Bodega> encontrados = new ArrayList<Bodega>();

		try {
			encontrados = session.createQuery("from Bodega").list();
		} catch (HibernateException ex) {
			logger.debug("Exception encontrada " + ex.getLocalizedMessage());
		} finally {
			session.close();
		}

		return encontrados;
	}

	@Override
	public Bodega obtenerBodega(int codigo) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Bodega encontrado = null;

		try {
			encontrado = (Bodega) session.get(Bodega.class, codigo);
		} catch (HibernateException ex) {
			logger.debug("Exception encontrada" + ex.getLocalizedMessage());
		} finally {
			session.close();
		}

		return encontrado;
	}

	@Override
	public void guardarBodega(Bodega bodega) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();

		try {
			session.save(bodega);
			session.getTransaction().commit();

		} catch (HibernateException ex) {
			logger.debug("Exception encontrada" + ex.getLocalizedMessage());
		} finally {
			session.close();
		}
		
	}

	@Override
	public void eliminarBodega(Bodega bodega) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();

		try {
			session.delete(bodega);
			session.getTransaction().commit();
		} catch (HibernateException ex) {
			logger.debug("Exception encontrada" + ex.getLocalizedMessage());
		} finally {
			session.close();
		}
		
	}

	@Override
	public void editarBodega(Bodega bodega) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();

		try {
			session.merge(bodega);
			session.getTransaction().commit();
		} catch (HibernateException ex) {
			logger.debug("Exception encontrada" + ex.getLocalizedMessage());
		} finally {
			session.close();
		}
		
	}

	@Override
	public List<Bodega> buscarBodega(String cadena) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Criteria criteria = session.createCriteria(Bodega.class);
		List<Bodega> encontrados = new ArrayList<Bodega>();

		try {
			criteria.add(Restrictions.like("cantProd", "%" + cadena + "%"));
			encontrados = criteria.list();
		} catch (HibernateException ex) {
			logger.debug("Exception encontrada" + ex.getLocalizedMessage());
		} finally {
			session.close();
		}

		return encontrados;
	}

}
